package com.aac.rabbitrfc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;

public class XmlDataUtil {

    private static final Logger LOG = LoggerFactory.getLogger(XmlDataUtil.class);

    public static String toString(Document xmldoc) {
        String result = "";
        if (xmldoc != null) {
            StringWriter strWtr = new StringWriter();
            StreamResult strResult = new StreamResult(strWtr);
            TransformerFactory tfac = TransformerFactory.newInstance();

            try {
                Transformer t = tfac.newTransformer();
                t.setOutputProperty("encoding", "UTF-8");
                t.setOutputProperty("indent", "yes");
                t.setOutputProperty("method", "xml");
                t.transform(new DOMSource(xmldoc.getDocumentElement()), strResult);
                result = strResult.getWriter().toString();
            } catch (Exception e) {
                LOG.error("XML文档对象转换字符串失败！", e, new String[0]);
            } finally {
                try {
                    strWtr.close();
                } catch (IOException e) {
                    LOG.error("字符串流关闭失败！", e, new String[0]);
                }

            }
        }

        return result;
    }

}
